package com.example.tivi.ui;

import io.vov.vitamio.LibsChecker;
import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.MediaPlayer.OnErrorListener;
import io.vov.vitamio.widget.MediaController;
import io.vov.vitamio.widget.VideoView;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.tivi.R;
import com.example.tivi.entity.Channel;
import com.example.tivi.entity.ChannelList;
import com.example.tivi.imageloader.ImageLoader;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.google.analytics.tracking.android.EasyTracker;

public class PlayerActivity extends FragmentActivity implements AdListener {

	public static final String EXTRA_DATA_CHANNEL_LIST = "EXTRA_DATA_CHANNEL_LIST";
	public static final String EXTRA_DATA_CHANNEL = "EXTRA_DATA_CHANNEL";

	private static final String TAG = "PlayerActivity";

	private VideoView mVideoView;
	private LinearLayout mllEmpty;
	private GridView mGridView;
	private Channel mChannelSelected;
	private LinearLayout mllHeader;
	private ImageView mimgActionbar;
	private TextView mtxtActionbarTitle;
	private FrameLayout mfrmVideo;

	/**
	 * Dung de chuyen dia chi url
	 */
	private int mChannelServer = 0;

	private AdView mAdView;
	private ImageView mimgClose;
	private RelativeLayout mllAd;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (!LibsChecker.checkVitamioLibs(this))
			return;

		// set always auto ratation
		Settings.System.putInt(getContentResolver(),
				Settings.System.ACCELEROMETER_ROTATION, 1);

		setContentView(R.layout.activity_player);
		initView();
		initAdView();

		Intent intent = getIntent();
		if (intent != null) {
			mChannelSelected = (Channel) intent
					.getSerializableExtra(EXTRA_DATA_CHANNEL);
			setTitle(mChannelSelected);
		}

		ChannelList channelList = (ChannelList) getIntent()
				.getSerializableExtra(EXTRA_DATA_CHANNEL_LIST);
		ChannelAdapter channelAdapter = new ChannelAdapter(this,
				channelList.getListChannel());

		mGridView.setAdapter(channelAdapter);
		mVideoView.setVideoURI(Uri.parse(mChannelSelected.getUrl().get(
				mChannelServer)));
	}

	@Override
	protected void onStart() {
		super.onStart();
		EasyTracker.getInstance().activityStart(this);
	}

	@Override
	protected void onStop() {
		super.onStop();
		EasyTracker.getInstance().activityStop(this);
	}

	@Override
	protected void onDestroy() {
		if (mAdView != null)
			mAdView.destroy();
		super.onDestroy();
	}

	private void setTitle(Channel channel) {
		String title = channel.getName() + " - " + channel.getDescription();
		mtxtActionbarTitle.setText(title);
	}

	private void initView() {
		mllEmpty = (LinearLayout) findViewById(R.id.activity_player_waiting);
		mGridView = (GridView) findViewById(R.id.activity_player_gridview);
		mllHeader = (LinearLayout) findViewById(R.id.layout_header);
		mimgActionbar = (ImageView) findViewById(R.id.header_img_actionbar);
		mimgClose = (ImageView) findViewById(R.id.activity_player_img_close);
		mllAd = (RelativeLayout) findViewById(R.id.activity_player_layout_adview);
		mtxtActionbarTitle = (TextView) findViewById(R.id.actionbarTitle);
		mfrmVideo = (FrameLayout) findViewById(R.id.activity_player_frm_video);

		mimgClose.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				mllAd.setVisibility(View.GONE);
			}
		});

		mimgActionbar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});

		mGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				mChannelServer = 0;
				Channel channel = (Channel) ((ChannelAdapter) arg0.getAdapter())
						.getItem(arg2);
				mVideoView.setVideoPath(channel.getUrl().get(mChannelServer));
				mllEmpty.setVisibility(View.VISIBLE);
				mChannelSelected = channel;
				setTitle(mChannelSelected);
				// hien thj lai quang cao
				mllAd.setVisibility(View.VISIBLE);
				
				EasyTracker.getInstance().setContext(getApplicationContext());
				EasyTracker.getTracker().sendEvent("Channel", channel.getName(), null, null);
			}
		});

		initViewVideo();
	}

	private void initAdView() {
		LinearLayout linearLayout = (LinearLayout) findViewById(R.id.lladView);

		mAdView = new AdView(this, AdSize.BANNER, "a151cb260fb3d7a");
		mAdView.setAdListener(this);
		linearLayout.addView(mAdView);

		AdRequest adRequest = new AdRequest();
		// TODO Xoa bo test Device
		adRequest.addTestDevice("C27236F177886F072102F9A4DD86EB78");
		mAdView.loadAd(adRequest);

	}

	private void initViewVideo() {

		mVideoView = (VideoView) findViewById(R.id.activity_player_surfaceview);
		mVideoView.setMediaController(new MediaController(this));
		mVideoView.requestFocus();
		mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
			@Override
			public void onPrepared(MediaPlayer mediaPlayer) {
				// optional need Vitamio 4.0
				// mediaPlayer.setPlaybackSpeed(1.0f);
				mllEmpty.setVisibility(View.GONE);
			}
		});
		mVideoView.setOnErrorListener(new OnErrorListener() {

			@Override
			public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
				EasyTracker.getInstance().setContext(PlayerActivity.this);

				String urlError = mChannelSelected.getUrl().get(mChannelServer);
				Log.e(TAG, "errror, link=" + mChannelServer);
				Log.e(TAG, "total link=" + mChannelSelected.getUrl().size()
						+ " url=" + urlError);

				EasyTracker.getTracker().sendEvent("ChannelError",
						mChannelSelected.getName(), urlError, 0L);
				mChannelServer++;
				if (mChannelServer < mChannelSelected.getUrl().size()) {
					mVideoView.setVideoPath(mChannelSelected.getUrl().get(
							mChannelServer));
					Log.d("Playagain",
							"path="
									+ mChannelSelected.getUrl().get(
											mChannelServer));
					return true;
				}
				return false;
			}
		});
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
		// updateFullscreenStatus(true);
		// mVideoView.setVideoLayout(3,0F);
		// mGridView.setVisibility(View.GONE);
		// mllHeader.setVisibility(View.GONE);
		// LayoutParams params=new LayoutParams(LayoutParams.MATCH_PARENT,
		// LayoutParams.MATCH_PARENT);
		// mfrmVideo.setLayoutParams(params);
		// mfrmVideo.invalidate();
		//
		// } else {
		// updateFullscreenStatus(false);
		// mVideoView.setVideoLayout(1,0F);
		// mGridView.setVisibility(View.VISIBLE);
		// mllHeader.setVisibility(View.VISIBLE);
		//
		// LayoutParams params=new LayoutParams(LayoutParams.MATCH_PARENT,
		// LayoutParams.WRAP_CONTENT);
		// params.height=getResources().getDimensionPixelSize(R.dimen.activity_player_frm_height);
		// mfrmVideo.setLayoutParams(params);
		// mfrmVideo.invalidate();
		// }
		displayForOrientation(newConfig);
	}

	private void displayForOrientation(Configuration configu) {
		if (configu.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			updateFullscreenStatus(true);
			mVideoView.setVideoLayout(3, 0F);
			mGridView.setVisibility(View.GONE);
			mllHeader.setVisibility(View.GONE);
			LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT);
			mfrmVideo.setLayoutParams(params);
			mfrmVideo.invalidate();
		} else {
			updateFullscreenStatus(false);
			mVideoView.setVideoLayout(1, 0F);
			mGridView.setVisibility(View.VISIBLE);
			mllHeader.setVisibility(View.VISIBLE);

			LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
					LayoutParams.WRAP_CONTENT);
			params.height = getResources().getDimensionPixelSize(
					R.dimen.activity_player_frm_height);
			mfrmVideo.setLayoutParams(params);
			mfrmVideo.invalidate();
		}
	}

	private void updateFullscreenStatus(boolean bUseFullscreen) {
		if (bUseFullscreen) {
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
			getWindow().clearFlags(
					WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		} else {
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
			getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		}
	}

	private static class ChannelAdapter extends BaseAdapter {
		private List<Channel> mlistChannel;
		private Context mContext;
		private ImageLoader mImageLoader;

		public ChannelAdapter(Context context, List<Channel> list) {
			mContext = context;
			mlistChannel = list;
			mImageLoader = new ImageLoader(mContext);
		}

		@Override
		public int getCount() {
			return mlistChannel.size();
		}

		@Override
		public Object getItem(int arg0) {
			return mlistChannel.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			ViewHolder holder = null;
			if (arg1 == null) {
				holder = new ViewHolder();
				arg1 = View.inflate(mContext,
						R.layout.item_list_relative_channel, null);
				holder.txt = (TextView) arg1
						.findViewById(R.id.item_list_relative_channel_txt);
				holder.img = (ImageView) arg1
						.findViewById(R.id.item_list_relative_channel_img);

				arg1.setTag(holder);
			} else {
				holder = (ViewHolder) arg1.getTag();
			}
			holder.txt.setText(mlistChannel.get(arg0).getName());
			mImageLoader.DisplayImage(mlistChannel.get(arg0).getUrlThumnail(),
					holder.img);
			return arg1;
		}

		private static class ViewHolder {
			public TextView txt;
			public ImageView img;
		}

	}

	@Override
	public void onDismissScreen(Ad arg0) {
		if (mVideoView != null)
			mVideoView.start();
	}

	@Override
	public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
	}

	@Override
	public void onLeaveApplication(Ad arg0) {
		mllAd.setVisibility(View.GONE);
	}

	@Override
	public void onPresentScreen(Ad arg0) {
	}

	@Override
	public void onReceiveAd(Ad arg0) {
		mllAd.setVisibility(View.VISIBLE);
	}
}
